package fun.tan90.easy.binlog.worker.handler;

import cn.hutool.json.JSONUtil;
import fun.tan90.easy.binlog.base.constants.EasyBinlogConstants;
import fun.tan90.easy.binlog.base.model.WorkerSystemResource;
import fun.tan90.easy.binlog.base.strategy.AbstractExecuteStrategy;
import lombok.extern.slf4j.Slf4j;
import org.noear.socketd.transport.core.Entity;
import org.noear.socketd.transport.core.Message;
import org.noear.socketd.transport.core.entity.StringEntity;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/12/15 19:42
 */
@Slf4j
@Component
public class WorkerSystemResourceHandler implements AbstractExecuteStrategy<Message, Entity> {

    @Resource
    MetricsEndpoint metricsEndpoint;

    @Override
    public String mark() {
        return EasyBinlogConstants.WORKER_SYSTEM_RESOURCE;
    }

    @Override
    public Entity executeResp(Message message) {
        List<String> heapTag = Collections.singletonList("area:heap");
        WorkerSystemResource workerSystemResource = WorkerSystemResource.builder()
                .jvmMemoryMax(metricsEndpoint.metric("jvm.memory.max", heapTag).getMeasurements().get(0).getValue())
                .jvmMemoryUsed(metricsEndpoint.metric("jvm.memory.used", heapTag).getMeasurements().get(0).getValue())
                .processCpuUsage(metricsEndpoint.metric("process.cpu.usage", null).getMeasurements().get(0).getValue())
                .systemCpuUsage(metricsEndpoint.metric("system.cpu.usage", null).getMeasurements().get(0).getValue())
                .build();
        return new StringEntity(JSONUtil.toJsonStr(workerSystemResource));
    }
}
